package mtvotingserver;

import java.io.*;
import java.net.*;

/**
 * An object which handles communication between the server and one client.
 * 
 * @author Alex Hrin (0807133)
 */
public class ClientRequest extends Thread{

    private VoteInterpreter interpreter;
    private Socket socket;

    /**
     * Constructor
     * 
     * @param interpreter the vote interpreter thread which gathers all client 
     * information
     * @param clientSocket the socket over which communication with the client 
     *                     will occur
     */
    public ClientRequest(VoteInterpreter interpreter, Socket clientSocket) {
        this.interpreter = interpreter;
        this.socket = clientSocket;
    }

    @Override
    public void run() {
        try {
            // create in/out buffers
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(socket.getInputStream())) ;
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
            
            //get client info
            String ipAddress = socket.getLocalAddress().getHostAddress();
            int port = socket.getLocalPort();
            String vote = StringTools.cleanString(in.readLine());
            
            //create new client
            ClientModel newClient = new ClientModel(ipAddress, port, vote);
            //try to find a similar client in the server history
            ClientModel oldClient = interpreter.getFromHistory(newClient);
            //client not found so this new client needs to be checked
            if (oldClient == null) {
                //search for a similar client in the active clients buffer
                oldClient = interpreter.getTempBuffer().confirm(newClient);
                //not found so we need to add him to the list
                if (oldClient == null) {
                    //first check if the vote is valid
                    if (interpreter.isValidOption(newClient.getClientVote()))
                    {
                        //push to the list of active clients
                        interpreter.getTempBuffer().add(newClient);
                        out.println("Vote cast. Vote a second time to "
                                + "confirm.");
                    }
                    else
                    {
                        //vote is invalid so the client gets ignored
                        out.println("Invalid vote cast. The option was not "
                                + "recognised.");
                    }
                }
                //found in the active clients list - vote can only be for 
                //confirmation purposes
                else {
                    //push the client to history
                    interpreter.pushToClientHistory(oldClient);
                    
                    //if the vote is valid
                    if (oldClient.isVoteValid())
                    {
                        //count it and confirm by sending back a message
                        interpreter.addVote(oldClient.getClientVote());
                        out.println("Second vote received - valid and "
                                + "registered.");
                    }
                    else
                    {
                        out.println("Second vote received - invalid.");
                    }
                   
                }
            }
            //if the client was found deny a second vote
            else {
                out.println("Vote already received from this IP. Ignored.");
            }
            
            socket.close();
        } catch (IOException ex) {
        }
    }
}
